/*
 File: ParseBlogOperation.m
 Abstract: The NSOperation class used to perform the XML parsing of magazine data.
 Version: 2.3
 
 Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple
 Inc. ("Apple") in consideration of your agreement to the following
 terms, and your use, installation, modification or redistribution of
 this Apple software constitutes acceptance of these terms.  If you do
 not agree with these terms, please do not use, install, modify or
 redistribute this Apple software.
 
 In consideration of your agreement to abide by the following terms, and
 subject to these terms, Apple grants you a personal, non-exclusive
 license, under Apple's copyrights in this original Apple software (the
 "Apple Software"), to use, reproduce, modify and redistribute the Apple
 Software, with or without modifications, in source and/or binary forms;
 provided that if you redistribute the Apple Software in its entirety and
 without modifications, you must retain this notice and the following
 text and disclaimers in all such redistributions of the Apple Software.
 Neither the name, trademarks, service marks or logos of Apple Inc. may
 be used to endorse or promote products derived from the Apple Software
 without specific prior written permission from Apple.  Except as
 expressly stated in this notice, no other rights or licenses, express or
 implied, are granted by Apple herein, including but not limited to any
 patent rights that may be infringed by your derivative works or by other
 works in which the Apple Software may be incorporated.
 
 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
 MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
 THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
 FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
 OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
 
 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
 MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
 AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
 STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 
 Copyright (C) 2010 Apple Inc. All Rights Reserved.
 
 */

#import "ParseBlogOperation.h"
#import "Blog.h"

// NSNotification name for sending blog data back to the app delegate
NSString *kAddBlogsNotif = @"AddBlogsNotif";

// NSNotification userInfo key for obtaining the blog data
NSString *kBlogResultsKey = @"BlogResultsKey";

// NSNotification name for reporting errors
NSString *kBlogsErrorNotif = @"BlogErrorNotif";

// NSNotification userInfo key for obtaining the error message
NSString *kBlogsMsgErrorKey = @"BlogsMsgErrorKey";


@interface ParseBlogOperation () <NSXMLParserDelegate>
@property (nonatomic, retain) Blog *currentBlogObject;
@property (nonatomic, retain) NSMutableArray *currentParseBatch;
@property (nonatomic, retain) NSMutableString *currentParsedCharacterData;
@end

@implementation ParseBlogOperation

@synthesize blogData, currentBlogObject, currentParsedCharacterData, currentParseBatch;
@synthesize magazineKey;

- (id)initWithData:(NSData *)parseData
{
    if (self = [super init]) {    
        blogData = [parseData copy];
    }
    return self;
}

- (void)addBlogsToList:(NSArray *)blogs {
    assert([NSThread isMainThread]);
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kAddBlogsNotif
                                                        object:self
                                                      userInfo:[NSDictionary dictionaryWithObject:blogs
                                                                                           forKey:kBlogResultsKey]]; 
}

// the main function for this NSOperation, to start the parsing
- (void)main {
    self.currentParseBatch = [NSMutableArray array];
	self.currentParsedCharacterData = [NSMutableString string];
	
	self.magazineKey = @"";
    
    // It's also possible to have NSXMLParser download the data, by passing it a URL, but this is
    // not desirable because it gives less control over the network, particularly in responding to
    // connection errors.
    //
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:self.blogData];
    [parser setDelegate:self];
    [parser parse];
    
    self.currentParseBatch = nil;
    self.currentBlogObject = nil;
    self.currentParsedCharacterData = nil;
    
    [parser release];
}

- (void)dealloc {
    [blogData release];
    
    [currentBlogObject release];
    [currentParsedCharacterData release];
    [currentParseBatch release];
    
    [super dealloc];
}


// Reduce potential parsing errors by using string constants declared in a single place.
static NSString * const kRootElementName =@"root";

static NSString * const kMagazineKeyElementName =@"magazineKey";

static NSString * const kBlogElementName=@"page";

static NSString * const kIndexAttributeName=@"num";
static NSString * const kTypeAttributeName=@"type";
static NSString * const kTitleAttributeName=@"title";
static NSString * const kIntroductionAttributeName=@"introduction";
static NSString * const kDetailurlAttributeName=@"detailurl";

#pragma mark -
#pragma mark NSXMLParser delegate methods

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
	attributes:(NSDictionary *)attributeDict {
	
    //NSLog(@"Element-----%@", elementName);
	
	if ([elementName isEqualToString:kRootElementName]) {
		;
	}
	else if ([elementName isEqualToString:kMagazineKeyElementName]){
		accumulatingParsedCharacterData = YES;
        [currentParsedCharacterData setString:@""];
	}
    else if ([elementName isEqualToString:kBlogElementName]) {
        Blog *blog = [[Blog alloc] init];
        self.currentBlogObject = blog;
        [blog release];
		
		NSString *index = (NSString *)[attributeDict objectForKey:kIndexAttributeName];
		self.currentBlogObject.index= [index intValue];
		
		NSString *type = (NSString *)[attributeDict objectForKey:kTypeAttributeName];
		self.currentBlogObject.type= type;
		
		NSString *title = (NSString *)[attributeDict objectForKey:kTitleAttributeName];
		self.currentBlogObject.title= title;
		
		NSString *introduction = (NSString *)[attributeDict objectForKey:kIntroductionAttributeName];
		self.currentBlogObject.introduction= introduction;
		
		NSString *detailurl = (NSString *)[attributeDict objectForKey:kDetailurlAttributeName];
		self.currentBlogObject.detailUrl= detailurl;
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName {
	if ([elementName isEqualToString:kRootElementName]) {
		[self performSelectorOnMainThread:@selector(addBlogsToList:)
                                   withObject:self.currentParseBatch
                                waitUntilDone:NO];
	}
	else if([elementName isEqualToString:kMagazineKeyElementName]) {
		NSScanner *scanner = [NSScanner scannerWithString:self.currentParsedCharacterData];
		NSString *magazineKeyString = nil;
		
		if ([scanner scanUpToCharactersFromSet:
			 [NSCharacterSet illegalCharacterSet] intoString:&magazineKeyString]) {
			self.magazineKey = magazineKeyString;
		}
	}
	else if ([elementName isEqualToString:kBlogElementName]) {
		if (![self.magazineKey isEqualToString:@""]) {
			self.currentBlogObject.magazineKey = self.magazineKey;
		}
		[self.currentParseBatch addObject:self.currentBlogObject];
    }
	
	// Stop accumulating parsed character data. We won't start again until specific elements begin.
    accumulatingParsedCharacterData = NO;

}

// This method is called by the parser when it find parsed character data ("PCDATA") in an element.
// The parser is not guaranteed to deliver all of the parsed character data for an element in a single
// invocation, so it is necessary to accumulate character data until the end of the element is reached.
//
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (accumulatingParsedCharacterData) {
        // If the current element is one whose content we care about, append 'string'
        // to the property that holds the content of the current element.
        //
        [self.currentParsedCharacterData appendString:string];
    }
}

// an error occurred while parsing the blog data,
// post the error as an NSNotification to our app delegate.
// 
- (void)handleBlogsError:(NSError *)parseError {
    [[NSNotificationCenter defaultCenter] postNotificationName:kBlogsErrorNotif
														object:self
													  userInfo:[NSDictionary dictionaryWithObject:parseError
																						   forKey:kBlogsMsgErrorKey]];
}

// an error occurred while parsing the item data,
// pass the error to the main thread for handling.
// (note: don't report an error if we aborted the parse due to a max limit of items)
//
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    if ([parseError code] != NSXMLParserDelegateAbortedParseError)
    {
        [self performSelectorOnMainThread:@selector(handleItemsError:)
                               withObject:parseError
                            waitUntilDone:NO];
    }
}

@end
